<template>
  <div style="min-height: 70vh;padding-bottom: 20px">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="关键词" prop="searchParam">
        <el-input
          v-model="queryParams.searchParam"
          placeholder="请输入通知关键词搜索"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleDateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发送用户" prop="sendUserType">
        <el-select
          v-model="queryParams.sendUserType"
          placeholder="用户类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in userTypeData"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="default"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="80" sortable />
      <el-table-column label="通知标题" align="center" prop="title" />
      <el-table-column label="通知内容" align="left" prop="content" show-overflow-tooltip />
      <el-table-column label="是否跳转" align="center" prop="skipBool" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.skipBool ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转链接" align="center" prop="skipUrl" />
      <el-table-column label="发送用户" align="center" prop="sendUserTypeStr" />
      <el-table-column label="发送时间" align="center" prop="sendTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="!scope.row.send"
            @click="handleRowSend(scope.row)"
          >发送</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="!scope.row.send"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            style="color: #f00"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改启动页对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="通知标题：" prop="title">
          <el-input v-model="form.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容：" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="封面图：" prop="frontPic">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.frontPic" :src="form.frontPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="发送用户：" prop="sendUserType" inline>
          <el-radio-group v-model="form.sendUserType">
            <el-radio :label="1">全部用户</el-radio>
            <el-radio :label="2">会员用户</el-radio>
            <el-radio :label="3">非会员用户</el-radio>
            <el-radio :label="4">单个用户</el-radio>
          </el-radio-group>
          <el-input v-if="form.sendUserType === 4" placeholder="输入单个用户ID" style="width: 150px;margin-left: 20px" v-model="form.singleUserId" />
        </el-form-item>
        <el-form-item label="是否跳转：" prop="skipBool">
          <el-switch v-model="form.skipBool" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="跳转链接：" prop="skipUrl" v-if="form.skipBool">
          <el-input v-model="form.skipUrl" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="定时发送：" prop="timingSend">
          <el-date-picker
            v-model="form.timingSend"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm">保 存</el-button>
        <el-button type="primary" @click="submitSend">发 送</el-button>
      </div>
    </el-dialog>

    <!--查看详情弹窗-->
    <el-dialog title="详情" :visible.sync="detail" width="50%" append-to-body :close-on-click-modal="false">
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;">通知标题：</span>
        <span>{{ content.title }}</span>
      </div>
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;">通知内容：</span>
        <span v-html="content.content" style="width: calc(100% - 80px)"></span>
      </div>
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;display: block;">封面图：</span>
        <el-image :src="content.frontPic" style="width: 240px"></el-image>
      </div>
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;">发送用户：</span>
        <span>{{ content.sendUserType }}</span>
      </div>
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;">是否跳转：</span>
        <span>{{ content.skip ? '是' : '否' }}</span>
      </div>
      <div style="display: flex;margin-bottom: 10px">
        <span style="width: 80px;text-align: right;">跳转链接：</span>
        <span>{{ content.skipUrl }}</span>
      </div>
      <div style="display: flex;">
        <span style="width: 80px;text-align: right;">定时发送：</span>
        <span>{{ content.timingSend }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getSystemNoticeList, saveSystemNotice, getSystemNoticeDetail, removeSystemNotice, sendSystemNotice } from "@/api/shuiyin/shuiyin";
  const userTypeData = [
    {
      label: '全部用户',
      value: 1
    },
    {
      label: '会员用户',
      value: 2
    },
    {
      label: '非会员用户',
      value: 3
    },
    {
      label: '单个用户',
      value: 4
    }
  ]
  export default {
    name: "SystemNoticeManage",
    data() {
      return {
        // 上传地址
        uploadAction: process.env.VUE_APP_BASE_API + "/common/ossUpload",
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 租户管理表格数据
        list: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查看详情弹出层
        detail: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          searchParam: undefined,
          sendBeginTime: undefined,
          sendEndTime: undefined,
          sendUserType: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          title: [
            { required: true, message: "通知标题不能为空", trigger: "blur" }
          ],
        },
        // 详情数据
        content: {},
        // 用户类型数据
        userTypeData: userTypeData
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询租户管理列表 */
      getList() {
        this.loading = true;
        getSystemNoticeList(this.queryParams).then(response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 日期时间选择组件确定事件
      handleDateChange(event) {
        this.queryParams.sendBeginTime = event[0];
        this.queryParams.sendEndTime = event[1];
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.queryParams.sendBeginTime = undefined;
        this.queryParams.sendEndTime = undefined;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          frontPic: '',
          content: null,
          sendUserType: 1,
          singleUserId: null,
          skipBool: false,
          skipUrl: null,
          show: false,
          timingSend: null,
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.form = JSON.parse(JSON.stringify(row))
        this.open = true;
        this.title = "修改";
      },
      /** 详情 */
      handleDetail(row) {
        const id = row.id || this.ids
        getSystemNoticeDetail(id).then(response => {
          this.content = JSON.parse(JSON.stringify(response.data))
        })
        this.detail = true;
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图标大小不能超过 2MB!');
        }
        return isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.form.frontPic = res.data;
      },
      /** 保存按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              saveSystemNotice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              saveSystemNotice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 发送按钮 */
      submitSend() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              sendSystemNotice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              sendSystemNotice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      handleRowSend(row) {
        const obj = {
          id: row.id
        }
        this.$modal.confirm('是否确认发送编号为"' + row.id + '"的数据项？').then(function() {
          return sendSystemNotice(obj);
        }).then(() => {
          this.$modal.msgSuccess("发送成功");
          this.getList();
        }).catch(() => {});
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
          return removeSystemNotice(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    }
  };
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
</style>
